package controle;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.Thread;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

import usuario.Usuario;

public class IniciaConexaoChatWorker extends Thread implements SocketControlConstants{

	private ControlePortas controlePortas;
	private int portaEntrada;
	private int portaSaida;
	private String ipFonte;
	private String ipDestino;
	private Usuario usuario;
	
	public IniciaConexaoChatWorker(String ipDestino, Usuario usuario){
		this.ipDestino = ipDestino;
		this.controlePortas = null;
		this.ipFonte = null;
		this.usuario = usuario;
	}
	
	public void run(){
			Socket socket;
		
		try
		{
				
			socket = new Socket(SocketControlConstants.ipServidor, SocketControlConstants.portaConexaoChatListener);
			ObjectOutputStream msg = new ObjectOutputStream(socket.getOutputStream());
			
			this.portaEntrada = Random();
			this.portaSaida = Random();
						
			System.out.println("portaEntrada: " + this.portaEntrada);
			System.out.println("portaSaida: " + this.portaSaida);
			
			this.controlePortas = new ControlePortas(this.portaEntrada, this.portaSaida, this.ipFonte, this.ipDestino);
			
			usuario.setPortaEntradaChat(this.portaEntrada);
			usuario.setPortaSaidaChat(this.portaSaida);
			msg.writeObject(this.controlePortas);
			socket.close();
			
		}
		 catch (UnknownHostException e) 
		 {
				e.printStackTrace();
		 } 
		 catch (IOException e) 
		 {
				e.printStackTrace();
		 } 
	}
	
	private int Random() 
	{
		return ( new Random().nextInt(SocketControlConstants.limSuperior - SocketControlConstants.limInferior) + (SocketControlConstants.limInferior) );
	}
}
